package com.xiaobai.yyds.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xiaobai.yyds.search.mapper.OrderRepository;
import com.xiaobai.yyds.search.service.OrderService;
import com.xiaobai.yyds.core.constant.HttpStatus;
import com.xiaobai.yyds.core.web.domain.AjaxResult;
import com.xiaobai.yyds.search.domain.Order;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author XIAOBAI
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Override
    public void saveAll(List<Order> orders) {
        orderRepository.saveAll(orders);
    }

    @Override
    public void deleteById(Integer id) {
        orderRepository.deleteById(id);
    }

    @Override
    public void updateById(Order order) {
        orderRepository.save(order);
    }

    @Override
    public AjaxResult selectByOrderDesc(String info) {
        NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(QueryBuilders.queryStringQuery(info)).build();
        SearchHits<Order> searchHits = elasticsearchRestTemplate.search(build, Order.class);
        if(searchHits.getTotalHits()<=0){
            return AjaxResult.error(HttpStatus.SUCCESS,"暂无此信息");
        }
        List<Order> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return searchProductList.size()>0 ?  AjaxResult.success(searchProductList): AjaxResult.error(HttpStatus.SUCCESS,"暂无此信息");
    }

    @Override
    public AjaxResult selectPageOrder(Integer page,Integer size, Integer sort, String sortProperties) {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(QueryBuilders.matchAllQuery());
        //分页
        nativeSearchQuery.setPageable(PageRequest.of(page,size));
        //排序
        if(sort==1){
            //1降序 desc
            nativeSearchQuery.addSort(Sort.by(Sort.Direction.DESC,sortProperties));
        }else {
            //0 升序 asc
            nativeSearchQuery.addSort(Sort.by(Sort.Direction.ASC,sortProperties));
        }
        SearchHits<Order> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, Order.class);
        if(searchHits.getTotalHits()<=0){
            return AjaxResult.error(HttpStatus.SUCCESS,"暂无此信息");
        }
        List<Order> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        long num =searchHits.getTotalHits();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("num",num);
        jsonObject.put("orderList",searchProductList);
        return searchProductList.size()>0 ?  AjaxResult.success(jsonObject):  AjaxResult.error(HttpStatus.SUCCESS,"暂无此信息");

    }

    @Override
    public Order findById(Integer id) {
        return orderRepository.findById(id).orElse(null);
    }

    @Override
    public AjaxResult getSearchOrder(String orderDesc, Integer sort, Integer pageNum, Integer pageSize, String sortProperties) {
        //orderDesc的色值
        String preTag = "<font color='#dd4b39'>";
        String postTag = "</font>";
        HighlightBuilder.Field field = new HighlightBuilder.Field("orderDesc").preTags(preTag).postTags(postTag);
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                //分页
                .withPageable(PageRequest.of(pageNum,pageSize))
                //设置高亮
                .withHighlightFields(field)
                //根据订单查询
                .withQuery(QueryBuilders.matchQuery("orderDesc",orderDesc))
                .build();
        //排序
        if(sort==1){
            //1降序 desc
            nativeSearchQuery.addSort(Sort.by(Sort.Direction.DESC,sortProperties));
        }else {
            //0 升序 asc
            nativeSearchQuery.addSort(Sort.by(Sort.Direction.ASC,sortProperties));
        }
        SearchHits<Order> search = elasticsearchRestTemplate.search(nativeSearchQuery, Order.class);
        List<SearchHit<Order>> searchHits = search.getSearchHits();
        if(searchHits.size()<=0){
            return   AjaxResult.error(HttpStatus.SUCCESS,"暂无此信息");
        }
        List<Order> orderList=new ArrayList<>();
        for (SearchHit<Order> searchHit:searchHits) {
            Order order=new Order();
            //取出非高亮数据
            Order content = searchHit.getContent();
            //取出高亮数据
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            if (highlightFields.containsKey("orderDesc")){
                order.setOrderDesc(highlightFields.get("orderDesc").toString());
                order.setOrderNo(content.getOrderNo());
                order.setOrderType(content.getOrderType());
                order.setId(content.getId());
                order.setOrderAmount(content.getOrderAmount());
                order.setUsername(content.getUsername());
                order.setUserPhone(content.getUserPhone());
            }
            orderList.add(order);
        }
        long num =search.getTotalHits();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("num",num);
        jsonObject.put("orderList",orderList);
        return  AjaxResult.success(jsonObject);
    }



}
